<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/07/13 16:08
 * Desc: 微信小程序登陆/注册
 */
class Model_Api_V2_Member_Wechat_Login extends ORM
{

    /**
     * @function 通过手机号登陆
     */
    public static function login_by_phone($params)
    {
        /**
         * @var $mobile
         * @var $openid
         * @var $unionid
         * @var $fxpcode
         * @var $nickname
         * @var $litpic
         */
        extract($params);

        $unionid = !empty($unionid) ? $unionid : $openid;
        if($mobile)
        {
            // 未登录状态
            $rs = Db::query(Database::SELECT,'(select * from `sline_member_third` where wx_mini_openid="' . $openid . '") union (select * from `sline_member_third` where openid="' . $unionid . '")')->execute()->current();
            if (!empty($rs))
            {
                if ($rs['openid'] != $unionid)
                {
                    //更改openId
                    DB::update('member_third')->set(array('openid' => $unionid))->where('id', '=', $rs['id'])->execute();
                    //整理多余用户
                    $richUser = DB::select()->from('member_third')->where('openid', '=', $unionid)->and_where('id', '<>', $rs['id'])->execute()->current();
                    if ($richUser)
                    {
                        DB::delete('member_third')->where('id', '=', $richUser['id'])->execute();
                        // DB::delete('member')->where('mid', '=',  $richUser['mid'])->execute();
                        DB::update('member_order')->set(array('memberid' => $rs['mid']))->where('memberid', '=', $richUser['mid'])->execute();
                    }
                }
                $reg_arr = array(
                    'nickname' => $nickname,
                    'litpic' => $litpic
                );
                $mid = $rs['mid'];
                // 检查会员是否存在
                $checkMember = DB::select()->from("member")->where("mid", "=", $mid)->execute()->current();
                if(!$checkMember){
                    // 如果不存在,则自动注册
                    $mid = St_Product::auto_reg($mobile,$reg_arr);
                    // 加入时间
                    Model_Member::add_reg_from($mid,4);
                    // 修改会员id
                    DB::update('member_third')->set(array('mid' => $mid))->where('mid', '=', $rs['mid'])->execute();
                }else{
                    if(!$checkMember['mobile']){
                        DB::update('member')->set(array('mobile' => $mobile))->where('mid', '=',$mid)->execute();
                    }
                }
                //这里补充记录微信的用户openid用于微信的相关应用操作.
                DB::update('member_third')->set(array('wx_mini_openid' => $openid))->where('mid', '=', $mid)->execute();
            }else{
                $reg_arr = array(
                    'nickname' => $nickname,
                    'litpic' => $litpic
                );
                //如果不存在,则自动注册
                $mid = St_Product::auto_reg($mobile,$reg_arr);
                //加入时间
                Model_Member::add_reg_from($mid,4);
                $data = array(
                    'mid' => $mid,
                    'wx_mini_openid' => $openid,
                    'openid' => $unionid,
                    'nickname' => $nickname,
                    'come_from' => 'weixin'
                );
                DB::insert('member_third',array_keys($data))->values(array_values($data))->execute();
            }

            if($mid)
            {
                //获取用户信息
                $member = Model_Member::member_find($mobile);
                $data   = Model_Api_V2_Member_Login::login_init($member);
                $result = array(
                    'status' => true,
                    'data'  => $data,
                    'msg'    => '登录成功'
                );

                // 检查是否安装分销商应用
                if(St_Functions::is_normal_app_install('mobiledistribution'))
                {
                    // 检查是否是分销商
                    $is_fenxiao = DB::select('fxcode','status')->from('fenxiao')->where('memberid','=',$mid)->execute()->current();
                    if(!$is_fenxiao && !empty($fxpcode))
                    { // 不是分销商且分销商fxcode不为空
                        Model_Fenxiao::invite($mid, $fxpcode);
                    }

                    if($is_fenxiao && $is_fenxiao['status'] == 1)
                    { // 是分销且分销状态为1
                        $result['fxcode'] = $is_fenxiao['fxcode'];
                    }
                }
            }
            else
            {
                $result = array(
                    'status' => false,
                    'msg'=> '用户信息有误'
                );
            }
        }
        else
        {
            $result = array(
                'status' => false,
                'msg'=> '请提交手机号码'
            );
        }

        return $result;
    }


    /**
     * @function 生成自定义的wxuid,用于多个小程序间的通信
     * @param $user_info
     * @return string
     */
    public static function generate_wxuid($user_info)
    {
        $user = json_decode($user_info, true);
        $litpic = $user['avatarUrl'];
        $city = $user['city'];
        $country = $user['country'];
        $gender = $user['gender'];
        $nickname = $user['nickname'];
        $province = $user['province'];
        $wxuid = md5($litpic . $city . $country . $gender . $nickname . $province);
        return $wxuid;
    }

    /**
     * @function 根据openid进行登录
     * @param $openid  // wx_mini_openid
     * @param $litpic
     * @param $nickname
     */
    public static function get_member_by_mini_openid($openid,$litpic,$nickname)
    {
        $result = array('status'=> false,'msg'=> '登录失败');
        if(!empty($openid))
        {
            $sql = "SELECT t.mid,m.mobile FROM sline_member_third t INNER JOIN sline_member m on(t.mid = m.mid) WHERE t.wx_mini_openid='{$openid}' and m.mobile <> '' LIMIT 1" ;
            $ar = DB::query(Database::SELECT, $sql)->execute()->current();

            if(!empty($ar['mid']))
            {
                $mid = $ar['mid'];
                // 更新用户信息
                $upData = array();
                if($litpic)
                {
                    $upData['litpic'] = $litpic;
                }
                if($nickname)
                {
                    $upData['nickname'] = $nickname;
                }
                if(!empty($upData))
                {
                    DB::update('member')->set($upData)->where("mid","=",$mid)->execute();
                }

                // 获取会员信息
                $member = DB::select()->from("member")->where("mid","=",$mid)->execute()->current();
                $data = Model_Api_V2_Member_Login::login_init($member);

                $result = array(
                    'status' => true,
                    'data'=> $data
                );
            }
        }

        return $result;
    }
}